﻿/*********************************************
 创建者：  george
 创建时间：2017-05-16
 功能说明：【端午节】KM小蓝单车积分兑换
 ********************************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Configuration;
using Activity.Data;

namespace Activity.API
{
    public class CreditExChangeHandler
    {
        /// <summary>
        /// 结束时间
        /// </summary>
        static readonly DateTime endDate = new DateTime(2017, 05, 31, 23, 59, 59);

        /// <summary>
        /// 开始时间
        /// </summary>
        static readonly DateTime beginDate = new DateTime(2017, 05, 27, 0, 0, 0);

        /// <summary>
        /// 测试
        /// </summary>
        static readonly string isDebug = WebConfigurationManager.AppSettings["isDebug"];

        static readonly string billNo= WebConfigurationManager.AppSettings["wx-acitvity-billNo"];
        /// <summary>
        /// 获取优惠券
        /// </summary>
        /// <param name="openId"></param>
        /// <returns></returns>
        CustomerInfo getCustomer(string openId)
        {
            var hk = new HKEntities();
            //获取是不是新注册会员,新会员赠送优惠券
            var regisCode = (
                from c in hk.KM_V_CardBinding
                join t in
                (from a in hk.Crm_Bas_THQInfo
                    join b in hk.Crm_Bas_THQDetail on a.THQID equals b.THQID
                    where b.BillNo == billNo && b.THQStatus == "1"
                    select new
                    {
                        a.THQID,
                        b.BillNo,
                        b.CustomerID,
                        b.THQStatus,
                        b.THQNo
                    }).DefaultIfEmpty() on
                c.CustomerID equals t.CustomerID
                into qq
                from m in qq.DefaultIfEmpty()
                where c.OpenID == openId
                select new
                {
                    m.THQID,
                    m.BillNo,
                    m.CustomerID,
                    m.THQStatus,
                    m.THQNo,
                    c.OpenID,
                    c.CardID,
                    c.CardCode,
                    c.MobileTel
                }).ToList().Select(t => new CustomerInfo()
            {
                BillNo = t.BillNo,
                CardID = t.CardID,
                CardCode = t.CardCode,
                Tel = t.MobileTel,
                CustomerID = t.CustomerID,
                OpenId = t.OpenID,
                THQID = t.THQID,
                THQNo = t.THQNo,
                THQStatus = t.THQStatus
            }).FirstOrDefault();
            return regisCode;
        }

        /// <summary>
        /// 检测商品是否已兑完(未使用)
        /// </summary>
        /// <returns></returns>
        public Messages IsExChange(string openId)
        {
            var rpt = new ActivityEntities();
            var exLogList = rpt.XL_ExChangeCode.ToList();
            var exCode = rpt.XL_ExChangeCode.ToList();
            var query = exCode.Except(exLogList).ToList();
            if (!query.Any())
                return new Messages {IsSuc = false, Code = -1, Message = "商品已兑完"};
            return new Messages {IsSuc = true, Code = 0, Message = $"{query.Count}"};
        }

        /// <summary>
        /// 检测用户信息 -1没有注册会员
        /// </summary>
        /// <param name="openId"></param>
        /// <returns></returns>
        public CustomerCredit CheckUserInfo(string openId)
        {
            //获取用户信息，返回昵称、积分,优惠券
            var hk = new HKEntities();
            var query = (from a in hk.CRM_Bas_CardInfo
                         join b in hk.KM_V_CardBinding on a.CardID equals b.CardID
                         where b.OpenID == openId select a ).FirstOrDefault();
            var result = new CustomerCredit
            {
                THQNo = getCustomer(openId)?.THQNo,
                Integral = query == null ? -1 : (int) query.RemainIntegral
            };
            return result;
        }

        /// <summary>
        /// 返回兑换列表
        /// </summary>
        /// <param name="openId"></param>
        /// <returns></returns>
        public List<ExChangeCode> GetList(string openId)
        {
            var rpt = new ActivityEntities();
            var list = (from c in rpt.XL_ExChangeCode
                        join b in rpt.XL_ExChageLog on c.XL_Code equals b.EC_Code
                        where b.OpenId == openId
                        select c).Select(t => new ExChangeCode
                        {
                            XL_Code = t.XL_Code
                        }).ToList();
            return list;
        }

        /// <summary>
        /// 兑换
        /// </summary>
        /// <param name="openId">openId</param>
        /// <param name="credit">积分</param>
        /// <returns></returns>
        public Messages ExChange(string openId,int credit)
        {
            if (string.IsNullOrWhiteSpace(openId)) return new Messages { IsSuc = false, Code = -1, Message = "无效的OPENID" };
            if (DateTime.Now < beginDate && isDebug.ToLower() == "false")
            {
                return new Messages { IsSuc = false, Code = -1, Message = "亲，活动还没开始呢" };
            }
            if (DateTime.Now >= endDate && isDebug.ToLower() == "false")
            {
                return new Messages { IsSuc = false, Code = -1, Message = "亲，活动已经结束了" };
            }
            //500积分起兑，每次以500积分倍数兑换
            var num = credit%500;
            if (num != 0)
                return new Messages { IsSuc = false, Code = -1, Message = "无效的积分" };

            var rpt = new ActivityEntities();
            var cartList = getCustomer(openId);
            if (cartList == null)
            {
                Log.WriteLog("没找到用户：OPENID:" + openId + "的微信会员");
                return new Messages { IsSuc = false, Code = -1, Message = "没找到微信会员" };
            }

            if(rpt.XL_ExChageLog.Any(t=>t.OpenId==openId))
                return new Messages { IsSuc = false, Code = -1, Message = "你已经兑换过了哦，亲!" };

            var exLogList = rpt.XL_ExChageLog.Select(t => t.EC_Code).ToList();
            var exCode = rpt.XL_ExChangeCode.Select(t => t.XL_Code).ToList();
            var query = exCode.Except(exLogList).ToList();
            //500积分当1000积分用
            var available = credit/500;
            if (available > query.Count)
                return new Messages { IsSuc = false, Code = -1, Message = "商品数量不够" };

            var _type = 1;
            if (!string.IsNullOrWhiteSpace(cartList.THQNo))
            {
                available = 1;
                _type = 2;
            }
            var result= query.Take(available).ToList();
            //记录兑换日志
            foreach (var item in result)
            {
                var add = new XL_ExChageLog
                {
                    EC_Date = DateTime.Now,
                    OpenId = openId,
                    Tel = cartList.Tel,
                    EC_Code = item,
                    EC_Type = _type,
                    RegisCode = string.IsNullOrWhiteSpace(cartList.THQNo) ? "" : cartList.THQNo
                };
                rpt.XL_ExChageLog.Add(add);
            }
            rpt.SaveChanges();
            //积分兑换才变更用户积分
            if (_type == 1)
                CalculateIntegral(cartList.CardID, cartList.CardCode, credit);
            else
                Modify(openId);
            return  new Messages { IsSuc = true, Code = 0, Message = "兑换成功" };
        }

        /// <summary>
        /// 修改优惠券状态
        /// </summary>
        /// <param name="openId"></param>
        void Modify(string openId)
        {
            if (isDebug.ToLower() == "true") return;
            var result = getCustomer(openId);
            var hk = new HKEntities();

            var detail = hk.Crm_Bas_THQDetail.FirstOrDefault(t=>t.BillNo==result.BillNo && t.CustomerID==result.CustomerID && t.THQNo==result.THQNo);
            if (detail != null)
                detail.THQStatus = "2";
            try
            {
                hk.SaveChanges();
                Log.WriteLog("用户编号 " + result.CardID + ",优惠券兑换小蓝单车券");
            }
            catch(Exception ex)
            {
                Log.WriteLog("用户编号 " + result.CardID + " 兑换出错:" + ex);
            }
        }

        /// <summary>
        /// 会员兑换积分实时更新到账户
        /// </summary>
        public void CalculateIntegral(string CardID, string CardCode,int Credit)
        {
            if (isDebug.ToLower() == "true") return;
            var dc = new HKEntities();
            var userInfo = dc.CRM_Bas_CardInfo.FirstOrDefault(t => t.CardID == CardID);
            if (userInfo != null)
            {
                userInfo.RemainIntegral -= Credit;
                userInfo.TotalIntegral -= Credit;
            }
            var billNo = "XL" + CardID + DateTime.Now.Ticks;
            var master = new CRM_Oper_AdjIntegralMaster
            {
                AdjIntegralType = "999",
                CompanyID = "KM",
                BillDate = DateTime.Now,
                BillNo = billNo,
                ShopID = "",
                BillStatus = 4,
                Finished = false,
                ModifyDTM = DateTime.Now,
                Remark = "2017端午节小蓝单车兑换券",
                BillTypeID = "Crm_Oper_AdjInt",
                IsPosBuild = false,
                Checker = "KM00000005",
                Operator = "KM00000005"
            };
            dc.CRM_Oper_AdjIntegralMaster.Add(master);
            var seq = DateTime.Now.Ticks.ToString();
            var detail = new CRM_Oper_AdjIntegralDetail
            {
                BillNo = master.BillNo,
                CompanyID = master.CompanyID,
                Sequence = seq,
                CardTypeID = "00000000000036",
                CardCode = CardCode,
                AdjustIntegral = Credit,
                NewIntegral = Credit,
                Remark = "2017端午节小蓝单车兑换券",
                ClearIntegralFlag = false,

            };
            dc.CRM_Oper_AdjIntegralDetail.Add(detail);
            try
            {
                dc.SaveChanges();
                Log.WriteLog("用户编号 " + CardID + ","+Credit+ "积分兑换小蓝单车券");
            }
            catch (Exception ex)
            {
                Log.WriteLog("用户编号 " + CardID + " 兑换出错:" + ex);
            }
        }
    }

    public class CustomerCredit
    {
        /// <summary>
        /// 优惠券
        /// </summary>
        public string THQNo { get; set; }

        /// <summary>
        /// 可用积分
        /// </summary>
        public int Integral { get; set; }
    }

    public class CustomerInfo
    {
        /// <summary>
        /// OpenId
        /// </summary>
        public string OpenId { get; set; }
        /// <summary>
        /// 会员ID
        /// </summary>
        public string CardID { get; set; }

        /// <summary>
        /// 会员编码
        /// </summary>
        public string CardCode { get; set; }

        /// <summary>
        /// 手机号
        /// </summary>
        public string Tel { get; set; }

        /// <summary>
        /// 优惠券ID
        /// </summary>
        public string THQID { get; set; }

        /// <summary>
        /// 活动ID
        /// </summary>
        public string BillNo { get; set; }

        /// <summary>
        /// 用户ID
        /// </summary>
        public string CustomerID { get; set; }

        /// <summary>
        /// 优惠券使用状态
        /// </summary>
        public string THQStatus { get; set; }

        /// <summary>
        /// 优惠券
        /// </summary>
        public string THQNo { get; set; }
        
    }

    public class UserInfo
    {
        /// <summary>
        /// OpenId
        /// </summary>
        public string OpenId { get; set; }
        /// <summary>
        /// 昵称
        /// </summary>
        public string NickName { get; set; }
        /// <summary>
        /// 可用积分
        /// </summary>
        public int Integral { get; set; }
    }

    public class ExChangeCode
    {
        /// <summary>
        /// 小蓝单车券
        /// </summary>
        public string XL_Code { get; set; }
        /// <summary>
        /// 有效开始时间
        /// </summary>
        public DateTime XL_BeginValidTime { get; set; }
        /// <summary>
        /// 有效结束时间
        /// </summary>
        public DateTime XL_EndValidTime { get; set; }
    }

    public class UserData
    {
        /// <summary>
        /// 昵称
        /// </summary>
        public string NickName { get; set; }
        /// <summary>
        /// 可用积分
        /// </summary>
        public int Integral { get; set; }
        /// <summary>
        /// 单车券列表
        /// </summary>
        public IList<ExChangeCode> List { get; set; }

        /// <summary>
        /// 优惠券
        /// </summary>
        public string THQNo { get; set; }
    }
}
